<?php

class IndexController extends Model3_Controller
{

    public function init()
    {

    }

    public function indexAction()
    {
        $this->view->message = '';

        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $auth = new Model3_Auth();

            if ($auth->authenticate($post['mail'], md5($post['pass'])))
            {
                $credentials = Model3_Auth::getCredentials();
                switch ($credentials['type'])
                {
                    case DefaultDb_Entities_User::USER_ADMIN :
                        $this->redirect('Admin/Dashboard');
                        break;
                    case DefaultDb_Entities_User::USER_DRIVER :
                        $this->redirect('Driver/Dashboard');
                        break;
                    case DefaultDb_Entities_User::USER_CLIENT :
                        $this->redirect('User/Dashboard');
                        break;
                    case DefaultDb_Entities_User::USER_STORER :
                        $this->redirect('Storer/Dashboard');
                        break;
                    case DefaultDb_Entities_User::USER_OPERATION_CONTROLLER:
                        $this->redirect('OperationController/Dashboard');
                        break;
                    default:
                        break;
                }
            }
            else
            {
                $this->view->message = "Usuario o password incorrecto";
            }
        }
    }

    public function registerAction()
    {

        $this->view->getJsManager()->addJs('jquery/jquery.min.v1.4.2.js');
        $this->view->getJsManager()->addJs('jquery/jquery.validate.js');
        $this->view->getJsManager()->addJs('tiny_mce/tiny_mce.js');
        $this->view->getJsManager()->addJs('tiny_mce/tiny_mce_src.js');
        $this->view->getJsManager()->addJs('text.js');
        $this->view->getJsManager()->addJs('register/register.js');
        $this->view->getJsManager()->addJs('sheepIt/jquery.sheepItPlugin-1.0.0.min.js');
        $this->view->getJsManager()->addJs('register/documents.js');
        $this->view->getJsManager()->addJs('jquery/jquery-ui-1.8.12.custom.min.js');
        $this->view->getJsManager()->addJs('register/autocomplete.js');

        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        /* @var $em Doctrine\ORM\EntityManager */

        $this->view->countries = $em->getRepository('DefaultDb_Entities_Countries')->getAllCountry();
        $this->view->areas = $em->getRepository('DefaultDb_Entities_GeographicalArea')->getAllAreas();
        $this->view->services = $em->getRepository('DefaultDb_Entities_Services')->getAllServices();
        $this->view->res = true;


//        $validator = new Model3_Validator_Form();
//        $ids = array("email", "pass", "firstName", "lastName", "company", "country", "cellPhone");
//        $datos = array("Email", "Password", "First Name", "Last Name", "Company", "Country", "Cell Phone");
//        foreach ($ids as $i => $id)
//        {
//            $validator->addValidation($id, Model3_Validator_Form::REQUIRED, null, 'The ' . $datos[$i] . ' field es required');
//        }
//        $validator->addValidation('pass', Model3_Validator_Form::MINLENGTH, 6, 'The password must be at least 6 digits');
//        $validator->addValidation('localNumber', Model3_Validator_Form::NUMERIC, null, 'The local Number fiels , must contain only numbers.');
//        $validator->addValidation('cellPhone', Model3_Validator_Form::NUMERIC, null, ',The Cell Phone fiels , must contain only numbers.');
        if ($this->getRequest()->isPost())
        {
            //if ($validator->validateForm())
            //{
            $post = $this->getRequest()->getPost();
            /* @var $user DefaultDb_Entities_User */
            $user = $em->getRepository('DefaultDb_Entities_User')->searchUserByEmail($post['email']);
            $country = $em->getRepository('DefaultDb_Entities_Countries')->find($post['country']);
            if ($user)
            {
                if ($user->getTypeLoginUser() == DefaultDb_Entities_User::USER_REGISTER)
                {
                    $dbs = Model3_Registry::getInstance()->get('databases');
                    $em = $dbs['DefaultDb'];

                    if ($post['pass'] == $post['confirmation'])
                    {
                        $user->setUsername($post['email']);
                        $user->setPassword(md5($post['pass']));
                        $user->setFirstName($post['firstName'], ENT_QUOTES, "UTF-8");
                        $user->setLastName($post['lastName']);
                        $user->setCompany($post['company']);
                        $user->setTitle($post['title']);
                        $user->setCountry($country);
                        $user->setCellPhone($post['cellPhone']);
                        $user->setLocalNumber($post['localNumber']);
                        $user->setCompanyUrl($post['companyUrl']);

                        $res = substr($post['linkFacebook'], 0, 7);
                        if (strcmp($res, 'http://') != 0 && strcmp($res, '') != 0)
                        {
                            $link = 'http://' . $post['linkFacebook'];
                            $user->setLinkFacebook($link);
                        }
                        else
                            $user->setLinkFacebook($post['linkFacebook']);

                        $res = substr($post['linkIn'], 0, 7);
                        if (strcmp($res, 'http://') != 0 && strcmp($res, '') != 0)
                        {
                            $link = 'http://' . $post['linkIn'];
                            $user->setLinkLinkedIn($link);
                        }
                        else
                            $user->setLinkLinkedIn($post['linkIn']);

                        $res = substr($post['linkMyspace'], 0, 7);
                        if (strcmp($res, 'http://') != 0 && strcmp($res, '') != 0)
                        {
                            $link = 'http://' . $post['linkMyspace'];
                            $user->setLinkMyspace($link);
                        }
                        else
                            $user->setLinkMyspace($post['linkMyspace']);

                        $res = substr($post['linkTwitter'], 0, 7);
                        if (strcmp($res, 'http://') != 0 && strcmp($res, '') != 0)
                        {
                            $link = 'http://' . $post['linkTwitter'];
                            $user->setLinkTwitter($link);
                        }
                        else
                            $user->setLinkTwitter($post['linkTwitter']);

                        $user->setTypeUser($post['typeUser']);
                        $user->setDescription($post['description']);

                        $user->setTypeLoginUser(DefaultDb_Entities_User::USER_COMMON);

                        $archiveHelper = new Helper_ArchiveHelper();
                        $headShot = $_FILES['headShot'];
                        if (strlen($headShot['name']) > 0)
                        {

                            $res = $archiveHelper->loadHeadShot($headShot, $user->getId());
                            if ($res['result'] === true)
                                $user->setHeadShot($res['path']);
                        }

                        foreach ($_FILES as $key => $file)
                        {
                            if (strstr($key, 'document'))
                            {
                                $aux = explode('_', $key);
                                $document = $_FILES['document_' . $aux[1]];
                                if (strlen($document['name']) > 0)
                                {
                                    $doc = new DefaultDb_Entities_DocumentsUser();
                                    $res = $archiveHelper->loadArchive($document, $user->getId());
                                    if ($res['result'] === true)
                                        $doc->setDocument($res['path']);
                                    $doc->setDocumentDescription($post['docDescription_' . $aux[1]]);
                                    $doc->setDocumentDateSent(new DateTime());
                                    $doc->setOwner($user);
                                    $em->persist($doc);
                                }
                            }
                        }
                        if (isset($post['area']))
                        {
                            $areas = $post['area'];
                            foreach ($areas as $area)
                            {
                                $areaGeographical = $em->find('DefaultDb_Entities_GeographicalArea', $area);
                                $user->addAreaGeographical($areaGeographical);
                            }
                        }
                        if (isset($post['service']))
                        {
                            $services = $post['service'];
                            foreach ($services as $service)
                            {
                                $userService = $em->find('DefaultDb_Entities_Services', $service);
                                $user->addUserService($userService);
                            }
                        }
                        $user->setTypeLoginUser(2);
                        $date = new DateTime;

                        $user->setAllowRequests(1);
                        $user->setUseBreak(0);
                        $user->setMeetingDuration(60);

                        $scheduleStart = new DateTime();
                        $scheduleStart->setTime(10, 0);
                        $scheduleEnd = new DateTime();
                        $scheduleEnd->setTime(20, 0);
                        $breakStart = new DateTime();
                        $breakStart->setTime(14, 0);
                        $breakEnd = new DateTime();
                        $breakEnd->setTime(15, 0);

                        $user->setScheduleStart($scheduleStart);
                        $user->setScheduleEnd($scheduleEnd);
                        $user->setBreakStart($breakStart);
                        $user->setBreakEnd($breakEnd);

                        $em->persist($user);
                        $em->flush();
                        $mailHelper = new Helper_MailHelper();
                        $mailHelper->sendMailWelcome($user->getUsername(), $user, $date);
                        $this->redirect('Index/index/register/success');
                    }
                    else
                    {
                        $this->view->res = false;
                        $this->view->errors = array("'confirmation of the password is incorrect'");
                    }
                }
                else
                {
                    $this->view->res = false;
                    $this->view->errors = array("User already registered!");
                }
            }
            else
            {
                $this->view->res = false;
                $this->view->errors = array("User not registered at WWC2011 yet!");
            }
            //}
//            else
//            {
//                $this->view->res = false;
//                $this->view->errors = $validator->getErrors();
//            }
        }
    }

    public function logoutAction()
    {
        Model3_Auth::deleteCredentials();
        $this->redirect('Index/index/');
    }

    public function recoverPassAction()
    {
        
    }

    public function sendPassAction()
    {
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];
            /* @var $userSearch DefaultDb_Entities_User */
            $userSearch = $em->getRepository('DefaultDb_Entities_User')->searchUserByEmail($post['email']);
            //var_dump($userSearch->getId());
            if ($userSearch)
            {
                $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
                $newPass = "";
                for ($i = 0; $i < 8; $i++)
                    $newPass .= substr($str, rand(0, 62), 1);
                //echo $newPass;
                //echo $userSearch->getId();
                $userSearch->setPassword(md5($newPass));
                $em->persist($userSearch);
                $em->flush();
                $helperMail = new Helper_MailHelper();
                $helperMail->sendPassword($post['email'], $newPass);
            }
            else
            {
                $this->view->res = false;
                $this->view->errors = array('This email not exist');
            }
        }
    }

    public function AxValidateEmailAction()
    {
        $this->view->setUseTemplate(false);
        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $dbs = Model3_Registry::getInstance()->get('databases');
            $em = $dbs['DefaultDb'];

            /* @var $userSearch DefaultDb_Entities_User */
            $user = $em->getRepository('DefaultDb_Entities_User')->searchUserByEmail($post['email']);
            if ($user && $user->getTypeLoginUser() == 3)
                $this->view->res = true;
        }
    }

    public function aboutDealAction()
    {
        
    }

    public function contactUsAction()
    {
        $this->view->getJsManager()->addJs('jquery/jquery.validate.js');
        $this->view->getJsManager()->addJs('contactUs/contactUs.js');

        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $event = new DefaultDb_Entities_Contacts();
        $admin = array('hector.benitez.fletes@gmail.com', 'cortestavo@gmail.com');
//        $admin = array('hector.benitez.fletes@gmail.com');

        if ($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            $event->setFirstName($post['firstName']);
            $event->setLastName($post['lastName']);
            $event->setUsername($post['username']);
            $event->setPnone($post['telephone']);
            $event->setEventName($post['eventName']);
            $event->setEventWebsite($post['eventWebsite']);
            $event->setComments($post['comments']);

            $date = new DateTime();
            $mailHelper = new Helper_MailHelper();
            foreach ($admin as $adm)
                $mailHelper->sendMailBusinessComercial($adm, $event, $post['comments'], $date);

            $em->persist($event);
            $em->flush();
        }
    }

    public function autocompleteAction()
    {
        $this->view->setUseTemplate(false);
        $dbs = Model3_Registry::getInstance()->get('databases');
        $em = $dbs['DefaultDb'];
        $company = array();

        $companies = $em->getRepository('DefaultDb_Entities_User')->findAllCompany();
        for ($i = 0; $i < count($companies); $i++)
        {
            $company[$i] = htmlentities($companies[$i]['company'] . '', ENT_QUOTES, 'ISO-8859-15');
            //$company[$i] = $companies[$i]['company'].'';  
        }
        $this->view->companies = $company;
    }
    
    public function bloquedUserAction()
    {
        
    }

}
